import { SubjectTypeEnum } from "@/enum/question-test/QuestionTestEnum";
import { XLSXJson } from "@/views/question/modules/types";

/**
 * 获取本地存储的试题数据
 * @param key 本地存储的键
 * @param type 题目类型
 * @example
 * getLocalSubjectData(); // ==>所有题目数据
 * getLocalSubjectData(SubjectTypeEnum.SINGLE); // ==>单选题数据
 */
export function getLocalSubjectData<T extends SubjectTypeEnum>(
  type?: T
): Array<XLSXJson> {
  const data = JSON.parse(
    localStorage.getItem(SubjectTypeEnum.ALL) || "[]"
  ) as Array<XLSXJson>;

  if (type === undefined || type === SubjectTypeEnum.ALL) {
    return data || [];
  }

  switch (type) {
    case SubjectTypeEnum.THREE_CHOICE:
      return data.filter((item) => item.select.length === 3) || [];
    case SubjectTypeEnum.TWO_CHOICE:
      return data.filter((item) => item.select.length === 2) || [];
    default:
      return data.filter((item) => item.subject === type) || [];
  }
}

/**
 * 将试题数据保存到本地
 */
export function saveLocalSubjectData(key: string, data: any) {
  localStorage.setItem(key, JSON.stringify(data));
}
